/**
 * Created by no1 on 2015/7/3.
 */
'use strict';

var DaoBase = require('./DaoBase');
var ShopModel = require('./models/shop.js');
var db = require('./models');
var util = require("util");
var F = require('../../function');

var debugLog = require('../../function.js').debugLog;


var defaultProject = {
  _id: 0,
  bitmapStatus: 0,
  smartSort: 0,
  __v: 0,
  __t: 0,
  otherInfo: 0

};

/**
 * 输出过滤
 * 过滤 'districtCode._id' 这个字段
 * @param doc
 * @private
 */
function __outputFilter(doc) {
  var list = [];
  if (Array.isArray(doc)) {
    list = list.concat(doc);
  } else {
    list.push(doc);
  }

  list.forEach(function (item) {
    var dis = item.district;
    if (!dis)return;
    dis.forEach(function (i) {
      if (i._id) delete i._id;
      if (i._doc && i._doc._id) delete i._doc._id;
    });
  });
}

function ShopDao(data) {
  data = data || {};
  data.model = data.model || db.shop;
  this.data = data;
  DaoBase.call(this, this.data);
}
util.inherits(ShopDao, DaoBase);

/**
 * @todo 删除商店,将其标志位改为delete
 * @param _id
 * @returns {*}
 */
ShopDao.prototype.deleteShop = function* (id) {
  var query = {id: id};
  var update = {status: 0};
  var result = yield this.model.findOneAndUpdate(query, update);
  return result;
};

/**
 * 根据地区代码,种类,查找店铺列表
 *
 * @param cityName
 * @param categories
 * @param limit
 * @param skip
 * @param sort
 * @returns {*}
 */
ShopDao.prototype.findByDistrictAndCate = function * (districtCode, cateCodes, limit, skip, sort) {
  var query = {
    //"categories.code": {$in: [cateCodes]},
    "district.code": {$in: [districtCode]},
    status: 1
  };
  if (cateCodes) {
    query["categories.code"] = {$in: [cateCodes]};
  }
  // debugLog(query);
  if (sort === 'grade') { // TODO other sort
    sort = {eTotal: -1};
  } else {
    sort = null;
  }

  var result;
  //var toExec = ShopModel.find(query, defaultProject).limit(limit).skip(skip);
  if (sort) {
    result = yield this.model.find(query, defaultProject).limit(limit).skip(skip).sort(sort).exec();
    //toExec = toExec.sort(sort);
  } else {
    result = yield this.model.find(query, defaultProject).limit(limit).skip(skip).exec();
  }
  result = result.map(function (item) {
    return item._doc;
  });
  // debugLog(result);
  __outputFilter(result);
  return result;
};

//var earthRadius = 6371; // km, miles is 3959
var earthRadius = 6371000; // m
function __toRadius(meter) {
  return meter / earthRadius;
}
function __toMeter(r) {
  var d = r * earthRadius;
  return d.toFixed(1);
}

// 返回列表
ShopDao.prototype.findByDistanceAndCate = function * (cord, radius, cateCodes, limit, skip, sort) {
  var query = {
    //categories: {$all: categories},
    //"categories.code": {$in: [cateCodes]},
    status: 1
  };

  if (cateCodes) {
    query["categories.code"] = {$in: [cateCodes]};
  }

  if (sort === 'grade') { // TODO other sort
    sort = {eTotal: -1};
  } else if (sort === 'smart') {
    sort = {smartSort: -1};
  } else {
    sort = null;
  }
  if (typeof skip === 'undefined') skip = 0;
  var match = {
    "$geoNear": {
      'near': cord,
      'spherical': true,
      'distanceField': 'dist',
      'includeLocs': 'loc',
      'query': query
    }
  };


  if (radius > 0) {
    var max = __toRadius(radius);
    match["$geoNear"].maxDistance = max;
  }
  var proj = {
    $project: {
      _id: 0,

      name: 1,
      id: 1,
      district: 1,
      loc: 1,
      image: 1,
      // tel: 1,
      address: 1,
      eTotal: 1,
      eCount: 1,
      eAverage: 1,
      discount: 1,
      reservation: 1,
      decorationGrade: 1,
      serviceGrade: 1,
      effectGrade: 1,
      dist: 1
      // status: 1
    }
  };
  var result = yield this.model.aggregate([match, proj, {$skip: skip}, {$limit: limit}, {$sort: sort}]).exec();
  result.forEach(function (item) {
    item.dist = __toMeter(item.dist);
  });

  __outputFilter(result);
  return result;
};

ShopDao.prototype.findById = function*(id) {
  var result = yield this.model.findOne({id: id}, defaultProject);
  if (!result) return F.returnData(1, 'no data', 3);
  return result._doc;
};



module.exports = ShopDao;
